package com.qls.web.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.qls.core.utils.R;


public class Sample {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // AccessKey ID
                .setAccessKeyId(accessKeyId)
                // AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public R sendMsg(String accessKeyId, String accessKeySecret, SendSmsRequest sendSmsRequest) {
        Client client = null;
        SendSmsResponseBody body = null;
        try {
            client = createClient(accessKeyId, accessKeySecret);
            body = client.sendSms(sendSmsRequest).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("发送失败");
        }

        if (body != null) {
            if ("OK".equals(body.getCode())) {
                return R.ok("短信发送成功");
            } else {
                return R.error(body.getMessage());
            }
        }
        return R.error("发送失败");

    }

}
